package com.example.sqliteprueba;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

public class RegistrarCargaActivity extends Activity {
	TextView txtFecha;
	TextView txtKms;
	TextView txtPrecio;
	TextView txtLitros;
	Button btnAceptar;
	Button btnCancelar;
	CheckBox chkTanqueLleno;
	private CargaDAO datasource;
	public static int RESULTADO_EXITOSO = 10;
	public static int RESULTADO_NO_EXITOSO = 20;
	Carga cargaAActualizar = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.registrar_carga);
		btnAceptar = (Button) findViewById(R.id.registrarCarga_btnAgregar);
		btnCancelar = (Button) findViewById(R.id.registrarCarga_btnCancelar);
		txtFecha = (TextView) findViewById(R.id.registrarCarga_txtFecha);
		txtKms = (TextView) findViewById(R.id.registrarCarga_txtKms);
		txtLitros = (TextView) findViewById(R.id.registrarCarga_txtLitros);
		txtPrecio = (TextView) findViewById(R.id.registrarCarga_txtPrecio);
		chkTanqueLleno = (CheckBox) findViewById(R.id.registrarCarga_chkTanqueLleno);

		datasource = new CargaDAO(this);
		datasource.open();

		btnAceptar.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				// EditText txt1 = (EditText) findViewById(R.id.editText1);
				// EditText txt2 = (EditText) findViewById(R.id.editText2);
				// EditText txt3 = (EditText) findViewById(R.id.editText3);
				// EditText txt4 = (EditText) findViewById(R.id.editText4);
				//
				if (!validar())
					return;
				if (cargaAActualizar == null) {
					Carga carga = new Carga();
					try {
						SimpleDateFormat sdf = new SimpleDateFormat(
								"dd-MM-yyyy");
						carga.setFecha(sdf.parse(String.valueOf(txtFecha
								.getText())));
					} catch (Exception ex) {
					}
					carga.setKm(Float.parseFloat(String.valueOf(txtKms
							.getText())));
					carga.setPrecio(Float.parseFloat(String.valueOf(txtPrecio
							.getText())));
					carga.setLitrosCargados(Float.parseFloat(String
							.valueOf(txtLitros.getText())));
					if (chkTanqueLleno.isChecked()) {
						carga.setTanqueLleno(true);
					} else {
						carga.setTanqueLleno(false);
					}
					datasource.createCarga(carga);
					hideKeyboard();
					setResult(RESULTADO_EXITOSO);
				} else {
					try {
						SimpleDateFormat sdf = new SimpleDateFormat(
								"dd-MM-yyyy");
						cargaAActualizar.setFecha(sdf.parse(String
								.valueOf(txtFecha.getText())));
					} catch (Exception ex) {
					}

					cargaAActualizar.setKm(Float.parseFloat(String
							.valueOf(txtKms.getText())));
					cargaAActualizar.setPrecio(Float.parseFloat(String
							.valueOf(txtPrecio.getText())));
					cargaAActualizar.setLitrosCargados(Float.parseFloat(String
							.valueOf(txtLitros.getText())));
					if (chkTanqueLleno.isChecked()) {
						cargaAActualizar.setTanqueLleno(true);
					} else {
						cargaAActualizar.setTanqueLleno(false);
					}
					datasource.createCarga(cargaAActualizar);
					hideKeyboard();
					setResult(RESULTADO_EXITOSO);
				}
				finish();
			}
		});

		btnCancelar.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				setResult(RESULTADO_NO_EXITOSO);
				finish();
			}
		});

		Bundle extras = getIntent().getExtras();

		// Carga carga = null;
		try {
			if (extras != null) {
				long id = extras.getLong("new_variable_name");
				cargaAActualizar = datasource.getCarga(id);
			}
		} catch (Exception ex) {
			Log.e("RegistrarCargaActivity", "Metodo onCreate");
		}

		if (cargaAActualizar == null) {
			Date hoy = new Date();
			SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy");
			// Get the date today using Calendar object.
			Date today = Calendar.getInstance().getTime();
			// Using DateFormat format method we can create a string
			// representation of a date with the defined format.
			String reportDate = df.format(today);
			txtFecha.setText(reportDate);
		} else {

			SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
			txtFecha.setText(sdf.format(cargaAActualizar.getFecha()));

			txtKms.setText(formatearFloat(cargaAActualizar.getKm()));
			txtLitros.setText(formatearFloat(cargaAActualizar
					.getLitrosCargados()));
			txtPrecio.setText(formatearFloat(cargaAActualizar.getPrecio()));
			chkTanqueLleno.setChecked(cargaAActualizar.isTanqueLleno());

		}
	}

	public String formatearFloat(float valor) {
		String aux = new DecimalFormat("#.##").format(valor);
		if (aux.endsWith(".00")) {
			aux = aux.replaceAll("\\.?0*$", "");
		}
		return aux;
	}

	private void hideKeyboard() {
		InputMethodManager inputManager = (InputMethodManager) this
				.getSystemService(Context.INPUT_METHOD_SERVICE);

		// check if no view has focus:
		View view = this.getCurrentFocus();
		if (view != null) {
			inputManager.hideSoftInputFromWindow(view.getWindowToken(),
					InputMethodManager.HIDE_NOT_ALWAYS);
		}
	}

	public boolean validar() {
		boolean res = true;
		String mensaje = "";
		try {
			if (String.valueOf(txtFecha.getText()).isEmpty()
					|| String.valueOf(txtKms.getText()).isEmpty()
					|| String.valueOf(txtPrecio.getText()).isEmpty()
					|| String.valueOf(txtLitros.getText()).isEmpty()) {
				res = false;
				mensaje = "Debe llenar todos los campos";
			} else {

				String.valueOf(txtFecha.getText());
				Float.parseFloat(String.valueOf(txtKms.getText()));
				Float.parseFloat(String.valueOf(txtPrecio.getText()));
				Float.parseFloat(String.valueOf(txtLitros.getText()));

				SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
				sdf.setLenient(false);
				sdf.parse(String.valueOf(txtFecha.getText()));
			}
		} catch (Exception ex) {
			res = false;
			mensaje = "Se ha producido un error en su ingreso de datos.";
		}

		if (!res) {
			AlertDialog alertDialog = new AlertDialog.Builder(
					RegistrarCargaActivity.this).create();
			alertDialog.setTitle("Error");
			alertDialog.setMessage(mensaje);
			alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {

					// here you can add functions

				}
			});
			alertDialog.show();
		}
		return res;
	}

	@Override
	protected void onResume() {
		// datasource.open();
		super.onResume();
	}

	@Override
	protected void onPause() {
		// datasource.close();
		super.onPause();
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		// Respond to the action bar's Up/Home button
		case android.R.id.home:
			NavUtils.navigateUpFromSameTask(this);
			// overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
			overridePendingTransition(android.R.anim.fade_in,
					android.R.anim.fade_out);
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

}
